package com.chinawlx.wlxteacher.ui.activity;

import android.content.Context;
import android.content.Intent;
import android.database.Cursor;
import android.net.Uri;
import android.os.Bundle;
import android.provider.MediaStore;
import android.text.InputFilter;
import android.text.InputType;
import android.text.TextUtils;
import android.view.View;
import android.view.inputmethod.InputMethodManager;
import android.widget.Button;
import android.widget.EditText;
import android.widget.ImageView;
import android.widget.ScrollView;
import android.widget.TextView;
import android.widget.Toast;

import com.bigkoo.alertview.AlertView;
import com.bigkoo.alertview.OnItemClickListener;
import com.bumptech.glide.Glide;
import com.chinawlx.wlxteacher.R;
import com.chinawlx.wlxteacher.network.WLXHttpRxHelper;
import com.chinawlx.wlxteacher.network.bean.WLXGetCodeBean;
import com.chinawlx.wlxteacher.utils.WLXConstant;
import com.chinawlx.wlxteacher.utils.WLXGreenDaoUtil;
import com.chinawlx.wlxteacher.utils.WLXLogUtil;
import com.chinawlx.wlxteacher.utils.WLXUIUtils;
import com.chinawlx.wlxteacher.widget.WLXCustomToast;
import com.chinawlx.wlxteacher.wlx_user;
import com.chinawlx.wlxteacher.wlx_userDao;

import java.io.File;
import java.io.IOException;
import java.util.List;

import butterknife.BindView;
import butterknife.ButterKnife;
import butterknife.OnClick;
import de.hdodenhof.circleimageview.CircleImageView;
import okhttp3.ResponseBody;
import rx.Subscriber;

/**
 * Created by wlx on 16/8/29.
 * 个人资料页面
 */
public class WLXPersonInfoActivity extends WLXBaseActivity {
    @BindView(R.id.iv_back_person_info)
    ImageView backBtn;
    @BindView(R.id.tv_nickname_person_info)
    TextView nickName;
    @BindView(R.id.tv_qq_person_info)
    TextView qq;
    @BindView(R.id.scrollview)
    ScrollView mScrollView;
    @BindView(R.id.et_nickname_person_info)
    EditText mEditText;
    @BindView(R.id.btn_cancel)
    Button cancelBtn;
    @BindView(R.id.btn_confirm)
    Button confirmBtn;
    @BindView(R.id.tv_name_person_info)
    TextView realName;
    @BindView(R.id.tv_sex_person_info)
    TextView sex;
    @BindView(R.id.tv_telephone_person_info)
    TextView telephone;
    @BindView(R.id.iv_icon_person_info)
    CircleImageView icon;
    private InputMethodManager mImm;
    private List<wlx_user> wlxUsers;
    private boolean isChangeQQ;

    private Uri mHeadUri;
    private File mHead;

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_person_info);
        mImm = (InputMethodManager) getSystemService(Context.INPUT_METHOD_SERVICE);
        ButterKnife.bind(this);
        try {
            mHead = new File(getExternalCacheDir() + "/head.jpg");
            mHead.createNewFile();
            mHeadUri = Uri.fromFile(mHead);
        } catch (IOException e) {
            e.printStackTrace();
        }
        init();
    }

    private void init() {
        initData();
        initView();
    }

    private void initData() {
        wlxUsers = WLXGreenDaoUtil.getUserDao().queryBuilder().where(wlx_userDao.Properties
                .User_id.eq(WLXConstant.USER_ID)).list();
    }

    private void initView() {
        wlx_user user = wlxUsers.get(0);
        if (user != null) {
            realName.setText(user.getRealname());
            nickName.setText(user.getNickname());
            sex.setText(user.getSex_code());
            qq.setText(user.getQq());
            telephone.setText(user.getMobile());
            Glide.with(this).load(user.getAvatar_url()).into(icon);
        }
    }

    @OnClick({R.id.iv_arrow2, R.id.iv_arrow3, R.id.iv_back_person_info, R.id
            .tv_nickname_person_info, R.id.iv_icon_person_info, R.id.tv_qq_person_info, R.id
            .btn_confirm, R.id.btn_cancel})
    public void onClick(View v) {
        switch (v.getId()) {
            case R.id.iv_back_person_info:
                finish();
                break;
            case R.id.iv_arrow1:
            case R.id.iv_icon_person_info:
                changeUserIcon();
                break;
            case R.id.iv_arrow2:
            case R.id.tv_nickname_person_info:
                changeNickName();
                break;
            case R.id.tv_qq_person_info:
            case R.id.iv_arrow3:
                changeQQ();
                break;
            case R.id.btn_confirm:
                editConfirm();
                break;
            case R.id.btn_cancel:
                mScrollView.setVisibility(View.GONE);
                mImm.toggleSoftInput(0, InputMethodManager.HIDE_NOT_ALWAYS);//隐藏软键盘
                mEditText.setText("");
                break;
        }
    }

    /**
     * 确认修改
     */
    private void editConfirm() {
        String text = mEditText.getText().toString().trim();
        if (TextUtils.isEmpty(text)) {
            Toast.makeText(this, "修改内容不能为空", Toast.LENGTH_SHORT).show();
        } else if (isChangeQQ) {
            requestNet("qq", text);
            qq.setText(text);
            mScrollView.setVisibility(View.GONE);
            mImm.toggleSoftInput(0, InputMethodManager.HIDE_NOT_ALWAYS);//隐藏软键盘
        } else {
            requestNet("nickname", text);
            nickName.setText(text);
            mScrollView.setVisibility(View.GONE);
            mImm.toggleSoftInput(0, InputMethodManager.HIDE_NOT_ALWAYS);//隐藏软键盘
        }
    }

    /**
     * 修改昵称和QQ号的网络请求
     *
     * @param filedName  类型
     * @param filedValue 值
     */
    private void requestNet(final String filedName, final String filedValue) {
        WLXHttpRxHelper.getInstance().changeNickNameAndQQ(filedName, filedValue, new
                Subscriber<ResponseBody>() {


                    @Override
                    public void onCompleted() {

                    }

                    @Override
                    public void onError(Throwable e) {

                    }

                    @Override
                    public void onNext(ResponseBody body) {
                        // TODO: 16/8/29 无json数据
                    }
                });
    }

    /**
     * 修改QQ
     */
    private void changeQQ() {
        mScrollView.setVisibility(View.VISIBLE);
        mEditText.setFocusable(true);
        mEditText.requestFocus();
        mEditText.setInputType(InputType.TYPE_CLASS_NUMBER);
        mEditText.setFilters(new InputFilter[]{new InputFilter.LengthFilter(12)});//限制最大舒服12个字符
        mEditText.setHint("请输入您的QQ号");
        mImm.toggleSoftInput(0, InputMethodManager.SHOW_FORCED);//弹出软键盘
        isChangeQQ = true;
    }

    /**
     * 修改昵称
     */
    private void changeNickName() {
        mScrollView.setVisibility(View.VISIBLE);
        mEditText.setFocusable(true);
        mEditText.requestFocus();
        mEditText.setHint("请输入您的昵称");
        mImm.toggleSoftInput(0, InputMethodManager.SHOW_FORCED);//弹出软键盘
        isChangeQQ = false;
    }


    //==========================更换头像 start=================================

    /* 请求识别码 */
    private static final int CODE_GALLERY_REQUEST = 0xa0;
    private static final int CODE_CAMERA_REQUEST = 0xa1;
    private static final int CODE_CROP_REQUEST = 0xa2;

    /* 头像文件 */
    private static final String IMAGE_FILE_NAME = "head_image.png";
    private File mFile;

    //更改用户头像
    private void changeUserIcon() {
        mFile = new File(WLXConstant.ExternalCacheDir, IMAGE_FILE_NAME);
        new AlertView("上传用户头像", null, "取消", null, new String[]{"拍照", "从相册中选择"}, this, AlertView
                .Style.ActionSheet, new OnItemClickListener() {
            @Override
            public void onItemClick(Object o, int position) {
                if (position == 0) {
                    getPictureFromPhotograph();
                } else if (position == 1) {
                    getPictureFromAlbume();
                }
            }
        }).show();
    }

    //从相册获取照片
    private void getPictureFromAlbume() {
        Intent intent = new Intent(Intent.ACTION_PICK, null);
        intent.setDataAndType(MediaStore.Images.Media.EXTERNAL_CONTENT_URI,
                "image/*");
        startActivityForResult(intent, CODE_GALLERY_REQUEST);
    }

    //拍照获取照片
    private void getPictureFromPhotograph() {
        //最好用try/catch包裹一下，防止因为用户未给应用程序开启相机权限，而使程序崩溃
        try {
            //开启相机应用程序获取并返回图片（capture：俘获）
            Intent intentFromCapture = new Intent(MediaStore.ACTION_IMAGE_CAPTURE);
            //指明存储图片或视频的地址URI:
            //注意，如果拍照的时候设置了MediaStore.EXTRA_OUTPUT，data.getData=null
            intentFromCapture.putExtra(MediaStore.EXTRA_OUTPUT, Uri.fromFile(mFile));
            startActivityForResult(intentFromCapture, CODE_CAMERA_REQUEST);//采用ForResult打开
        } catch (Exception e) {
            WLXCustomToast.show("相机无法启动，请先开启相机权限");
        }
    }

    @Override
    protected void onActivityResult(int requestCode, int resultCode, Intent data) {
        // 用户没有进行有效的设置操作，返回
        if (resultCode == RESULT_CANCELED) {
            WLXCustomToast.show("取消");
            return;
        }
        switch (requestCode) {
            case CODE_GALLERY_REQUEST://相册的
                if (data != null) {
                    //============调用系统的裁剪================
                    Intent intent = new Intent("com.android.camera.action.CROP");
                    intent.setDataAndType(data.getData(), "image/*");
                    // 下面这个crop=true是设置在开启的Intent中设置显示的VIEW可裁剪
                    intent.putExtra("return-data", false);//不直接通过intent传递数据，
                    intent.putExtra(MediaStore.EXTRA_OUTPUT, mHeadUri);//直接输出文件
                    startActivityForResult(intent, CODE_CROP_REQUEST);
                }
                break;
            case CODE_CAMERA_REQUEST://拍摄的
                requestNet4UploadIcon(mFile.getAbsolutePath());
                break;
            case CODE_CROP_REQUEST://预备剪裁用的
                requestNet4UploadIcon(mHead.getAbsolutePath());
                break;
        }
        super.onActivityResult(requestCode, resultCode, data);
    }

    /**
     * 提取保存裁剪之后的图片数据，并设置头像部分的View
     */
    private void requestNet4UploadIcon(String path) {
        if (!TextUtils.isEmpty(path)) {
            WLXUIUtils.zoomBitmap(path, 480, 640);
            try {
                File file = new File(path);
                WLXLogUtil.d("size："+file.length());
                uploadUserAvatar(file);
            } catch (Exception e) {
                e.printStackTrace();
            }
        }
    }

    //上传用户头像
    private void uploadUserAvatar(File file) {
        WLXHttpRxHelper.getInstance().uploadTeacherAvatar(file, new Subscriber<WLXGetCodeBean>() {
            @Override
            public void onCompleted() {
                List<wlx_user> list = WLXGreenDaoUtil.getUserDao().queryBuilder().where
                        (wlx_userDao.Properties.User_id.eq(WLXConstant.USER_ID)).list();
                if (list.size() > 0) {
                    wlx_user user = list.get(0);
                    String avatar_url = user.getAvatar_url();
                    Glide.with(WLXPersonInfoActivity.this).
                            load(avatar_url).dontAnimate().centerCrop().placeholder(R.drawable
                            .place_holder).into(icon);
                }
            }

            @Override
            public void onError(Throwable e) {
                WLXLogUtil.d("error: " + e.getMessage());
                onCompleted();
            }

            @Override
            public void onNext(WLXGetCodeBean WLXGetCodeBean) {
                if (WLXGetCodeBean.getCode() == 0) {
                    List<wlx_user> list = WLXGreenDaoUtil.getUserDao().queryBuilder().where
                            (wlx_userDao.Properties.User_id.eq(WLXConstant.USER_ID)).list();
                    if (list.size() > 0) {
                        wlx_user user = list.get(0);
                        user.setAvatar_url(WLXGetCodeBean.getData());
                        WLXGreenDaoUtil.getUserDao().update(user);
                    }
                    WLXCustomToast.show("上传头像成功");
                } else {
                    WLXCustomToast.show("上传头像失败,请重试!");
                }
            }
        });
    }

    //==========================更换头像 end=================================


}
